<script setup>
import { ref, reactive, onMounted, nextTick, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Search,
  Edit,
  View,
  Delete,
  RefreshRight,
  DataLine,
} from "@element-plus/icons-vue";
import {
  getDailyLogList,
  addDailyLog,
  updateDailyLog,
  deleteDailyLog,
  getDailyCoreStats,
  getDailyFoodCosts,
} from "../../api/dailyLogs";

import Drawer from "../../components/Drawer.vue";
import DailyStatsCard from "./components/DailyStatsCard.vue";

const loading = ref(false);
const tableData = ref([]);
const total = ref(0);
const coreStats = ref({});

// 每日状况的固定选项
const eatTimeOptions = [
  { value: 1, label: "早餐" },
  { value: 2, label: "中餐" },
  { value: 3, label: "晚餐" },
  { value: 0, label: "全天" },
];

// 星期选项
const weekOptions = [
  { value: "星期一", label: "星期一" },
  { value: "星期二", label: "星期二" },
  { value: "星期三", label: "星期三" },
  { value: "星期四", label: "星期四" },
  { value: "星期五", label: "星期五" },
  { value: "星期六", label: "星期六" },
  { value: "星期日", label: "星期日" },
];

// 搜索和分页
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  startDate: "",
  endDate: "",
  log_week: null,
  eat_time: null,
  remark: "",
});

// 默认日期
let defaultStartDate = "";
let defaultEndDate = "";

// 搜索表单
const searchForm = reactive({
  startDate: "",
  endDate: "",
  log_week: null,
  eat_time: null,
  remark: "",
});

const defaultFormData = {
  id: null,
  log_date: "",
  eat_time: 0,
  meal_count: null,
  meal_sales: null,
  qcode_count: null,
  qcode_sales: null,
  card_count: null,
  card_sales: null,
  ticket_count: null,
  ticket_sales: null,
  food_cost: null,
  room_food_sales: null,
  room_food_cost: null,
  remark: "",
};
const formData = reactive({ ...defaultFormData });
const formRef = ref(null);

const computedNonRoomTotalSales = computed(() => {
  const nonRoomSales =
    (Number(formData.meal_sales) || 0) +
    (Number(formData.qcode_sales) || 0) +
    (Number(formData.card_sales) || 0) +
    (Number(formData.ticket_sales) || 0);

  return nonRoomSales;
});

const rules = reactive({
  log_date: [{ required: true, message: "请选择日志日期", trigger: "change" }],
  eat_time: [{ required: true, message: "请选择就餐时段", trigger: "change" }],
  meal_count: [
    { required: true, message: "包餐人数不能为空", trigger: "blur" },
  ],
  meal_sales: [
    { required: true, message: "包餐营业额不能为空", trigger: "blur" },
  ],
  qcode_count: [
    { required: true, message: "扫码人数不能为空", trigger: "blur" },
  ],
  qcode_sales: [
    { required: true, message: "扫码营业额不能为空", trigger: "blur" },
  ],
  card_count: [
    { required: true, message: "刷卡人数不能为空", trigger: "blur" },
  ],
  card_sales: [
    { required: true, message: "刷卡营业额不能为空", trigger: "blur" },
  ],
  ticket_count: [
    { required: true, message: "餐票人数不能为空", trigger: "blur" },
  ],
  ticket_sales: [
    { required: true, message: "餐票营业额不能为空", trigger: "blur" },
  ],
  total_sales: [
    { required: true, message: "总营业额不能为空", trigger: "blur" },
  ],
  food_cost: [
    { required: true, message: "食材总成本不能为空", trigger: "blur" },
  ],
  room_food_sales: [
    { required: true, message: "包间营业额不能为空", trigger: "blur" },
  ],
  room_food_cost: [
    { required: true, message: "包间食材成本不能为空", trigger: "blur" },
  ],
});

const drawer = reactive({
  visible: false,
  title: "",
  type: "add",
  id: null,
});

let originalFormData = null;

const formatRatio = (value) => {
  if (value === null || value === undefined) return "0.00%";
  return (Number(value) * 100).toFixed(2) + "%";
};

const formatCurrency = (value) => {
  if (value === null || value === undefined) return "0.00";
  return Number(value).toFixed(2);
};

const indexMethod = (index) => {
  return index + 1 + (queryParams.page - 1) * queryParams.pageSize;
};

// 获取成本
async function fetchCostsForDate() {
  const date = formData.log_date;

  if (!date) {
    ElMessage.warning("请先选择日志日期");
    return;
  }

  loading.value = true;
  try {
    const res = await getDailyFoodCosts(date);

    if (res.code === 0 && res.data) {
      const { food_cost, room_food_cost } = res.data;

      formData.food_cost = String(Number(food_cost || 0).toFixed(2));
      formData.room_food_cost = String(Number(room_food_cost || 0).toFixed(2));

      ElMessage.success(`成功获取 ${date} 的成本数据`);
    } else {
      ElMessage.error(res.msg || `获取 ${date} 成本数据失败，已重置为 0.00`);
      formData.food_cost = "0.00";
      formData.room_food_cost = "0.00";
    }
  } catch (error) {
    console.error("获取成本数据失败:", error);
    ElMessage.error("获取成本数据失败，请检查网络或后端服务，已重置为 0.00");
    formData.food_cost = "0.00";
    formData.room_food_cost = "0.00";
  } finally {
    loading.value = false;
  }
}

// 核心统计数据
async function loadCoreStats() {
  try {
    const res = await getDailyCoreStats({
      startDate: queryParams.startDate,
      endDate: queryParams.endDate,
      log_week: queryParams.log_week,
      eat_time: queryParams.eat_time,
      remark: queryParams.remark,
    });
    if (res.code === 0 && res.data) {
      coreStats.value = res.data;
    } else {
      coreStats.value = {};
    }
  } catch (error) {
    console.error("获取核心统计数据失败:", error);
    coreStats.value = {};
  }
}

// 获取列表
async function loadDailyLogList(resetPage = false) {
  if (resetPage) {
    queryParams.page = 1;
  }
  loading.value = true;
  try {
    const params = {
      page: queryParams.page,
      pageSize: queryParams.pageSize,
      startDate: queryParams.startDate,
      endDate: queryParams.endDate,
      log_week: queryParams.log_week,
      eat_time: queryParams.eat_time,
      remark: queryParams.remark,
    };

    const res = await getDailyLogList(params);

    if (res.code === 0) {
      const logData = Array.isArray(res.data) ? res.data : res.data?.data || [];
      const pagination = res.pagination || res.data?.pagination || {};

      tableData.value = logData.map((item) => {
        const logDate = item.log_date ? item.log_date.split("T")[0] : "";
        const displayEatTime = item.eat_time;

        return {
          ...item,
          id: item.id,
          log_date: logDate,
          eat_time: displayEatTime,
          total_sales: item.total_sales || "0.00",
          food_cost: item.food_cost || "0.00",
          room_food_sales: item.room_food_sales || "0.00",
          eat_time_text:
            eatTimeOptions.find((opt) => opt.value === displayEatTime)?.label ||
            "未知",
        };
      });

      total.value = pagination.total || 0;
      queryParams.page = pagination.page || 1;
      queryParams.pageSize = pagination.pageSize || queryParams.pageSize;
    } else {
      ElMessage.error(res.msg || "获取每日状况列表失败");
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取每日状况列表失败:", error);
    ElMessage.error("获取每日状况列表失败，请检查网络服务");
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

// 初始化加载数据
function initialLoad() {
  const today = new Date();
  const tenDaysAgo = new Date();
  tenDaysAgo.setDate(today.getDate() - 9);

  const formatDate = (date) => date.toISOString().slice(0, 10);

  defaultStartDate = formatDate(tenDaysAgo);
  defaultEndDate = formatDate(today);

  searchForm.startDate = defaultStartDate;
  searchForm.endDate = defaultEndDate;
  searchForm.log_week = null;
  searchForm.eat_time = null;
  searchForm.remark = "";

  handleSearch();
}

// 搜索/筛选
const handleSearch = () => {
  queryParams.startDate = searchForm.startDate;
  queryParams.endDate = searchForm.endDate;
  queryParams.log_week = searchForm.log_week;
  queryParams.eat_time = searchForm.eat_time;

  loadDailyLogList(true);
  loadCoreStats();
};

const handleReset = () => {
  // 重置
  searchForm.startDate = defaultStartDate;
  searchForm.endDate = defaultEndDate;
  searchForm.log_week = null;
  searchForm.eat_time = null;

  handleSearch();
};

// 日期按钮
const quickDateSelect = (type) => {
  const end = new Date();
  const start = new Date();
  start.setDate(end.getDate() - (type === "week" ? 6 : 29));

  const formatDate = (date) => date.toISOString().slice(0, 10);

  searchForm.startDate = formatDate(start);
  searchForm.endDate = formatDate(end);
  searchForm.log_week = null;
  searchForm.eat_time = null;
  searchForm.remark = "";

  handleSearch();
};

// 检查表单数据
const checkFormModified = () => {
  if (drawer.type === "add") {
    const keysToExclude = ["id", "log_date", "eat_time"];
    const keysToCompare = Object.keys(defaultFormData).filter(
      (k) => !keysToExclude.includes(k)
    );
    for (const key of keysToCompare) {
      const defaultValue = defaultFormData[key];
      const currentValue = formData[key];

      if (Array.isArray(currentValue) && Array.isArray(defaultValue)) {
      } else if (String(currentValue || "") !== String(defaultValue || "")) {
        return true;
      }
    }
    return false;
  } else if (drawer.type === "edit" && originalFormData) {
    const keysToCompare = Object.keys(defaultFormData).filter(
      (k) => k !== "id"
    );
    for (const key of keysToCompare) {
      const currentVal = formData[key];
      const originalVal = originalFormData[key];

      if (Array.isArray(currentVal) && Array.isArray(originalVal)) {
      } else if (String(currentVal || "") !== String(originalVal || "")) {
        return true;
      }
    }
    return false;
  }
  return false;
};

const openDrawer = (type, row = null) => {
  drawer.type = type;

  originalFormData = null;

  if (type === "add") {
    Object.assign(formData, defaultFormData);
    formData.log_date = new Date().toISOString().slice(0, 10);
    formData.eat_time = 0;
  } else if (row) {
    const processedEatTime =
      row.eat_time === null ? null : Number(row.eat_time);
    const newFormData = {
      id: row.id,
      log_date: row.log_date || "",
      eat_time: processedEatTime,
      remark: row.remark || "",

      meal_count: Number(row.meal_count) || 0,
      qcode_count: Number(row.qcode_count) || 0,
      card_count: Number(row.card_count) || 0,
      ticket_count: Number(row.ticket_count) || 0,

      meal_sales: String(row.meal_sales || "0.00"),
      qcode_sales: String(row.qcode_sales || "0.00"),
      card_sales: String(row.card_sales || "0.00"),
      ticket_sales: String(row.ticket_sales || "0.00"),
      food_cost: String(row.food_cost || "0.00"),
      total_sales: String(row.total_sales || "0.00"),
      room_food_cost: String(row.room_food_cost || "0.00"),
      room_food_sales: String(row.room_food_sales || "0.00"),
    };
    Object.assign(formData, newFormData);
    if (type === "edit") {
      originalFormData = JSON.parse(JSON.stringify(newFormData));
    }
  }

  drawer.title =
    type === "add"
      ? "新增每日经营状况记录"
      : type === "edit"
      ? "编辑每日经营状况记录"
      : "查看每日经营状况详情";
  drawer.id = row ? row.id : null;
  drawer.visible = true;

  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 弹窗确认关闭抽屉
const handleCloseDrawer = (done) => {
  if (drawer.type === "view") {
    done();
    return;
  }

  if (!checkFormModified()) {
    done();
    return;
  }

  ElMessageBox.confirm(
    "当前表单数据尚未保存，确定放弃修改并关闭吗?",
    "放弃修改并关闭",
    {
      confirmButtonText: "确定放弃",
      cancelButtonText: "返回编辑",
      type: "warning",
      closeOnClickModal: false,
    }
  )
    .then(() => {
      done();
    })
    .catch(() => {
      // 返回编辑
    });
};

// 抽屉底部的取消按钮
const handleCancel = () => {
  if (drawer.type === "view") {
    drawer.visible = false;
    return;
  }

  if (!checkFormModified()) {
    drawer.visible = false;
    return;
  }

  ElMessageBox.confirm(
    "当前表单数据尚未保存，确定放弃修改并关闭吗?",
    "放弃修改并关闭",
    {
      confirmButtonText: "确定放弃并关闭",
      cancelButtonText: "返回编辑",
      type: "warning",
      closeOnClickModal: false,
    }
  )
    .then(() => {
      // 取消操作，直接关闭
      drawer.visible = false;
    })
    .catch(() => {
      // 留在抽屉
    });
};

const handleSave = async () => {
  const valid = await formRef.value.validate((isValid, fields) => {
    if (!isValid) {
      console.error("表单校验失败:", fields);
    }
    return isValid;
  });
  if (!valid) {
    ElMessage.error("请检查表单输入是否正确");
    return;
  }

  // 组装用于确认的消息
  const logInfo = `【${formData.log_date} ${
    eatTimeOptions.find((opt) => opt.value === formData.eat_time)?.label
  }】`;

  // 保存确认
  ElMessageBox.confirm(
    `确认要${
      drawer.type === "add" ? "新增" : "更新"
    }每日状况记录 ${logInfo} 吗?`,
    "操作确认",
    {
      confirmButtonText: "确定保存",
      cancelButtonText: "取消",
      type: "info",
    }
  )
    .then(async () => {
      await executeSubmit();
    })
    .catch(() => {
      ElMessage.info("已取消保存");
    });
};

// 提交
const executeSubmit = async () => {
  let apiCall;
  let successMsg = "";
  const data = {
    log_date: formData.log_date,
    eat_time: Number(formData.eat_time),
    remark: formData.remark,
    meal_count: Number(formData.meal_count),
    qcode_count: Number(formData.qcode_count),
    card_count: Number(formData.card_count),
    ticket_count: Number(formData.ticket_count),
    meal_sales: Number(formData.meal_sales).toFixed(2),
    qcode_sales: Number(formData.qcode_sales).toFixed(2),
    card_sales: Number(formData.card_sales).toFixed(2),
    ticket_sales: Number(formData.ticket_sales).toFixed(2),
    total_sales: computedNonRoomTotalSales.value.toFixed(2),
    food_cost: Number(formData.food_cost).toFixed(2),
    room_food_cost: Number(formData.room_food_cost).toFixed(2),
    room_food_sales: Number(formData.room_food_sales).toFixed(2),
  };

  if (drawer.type === "add") {
    apiCall = addDailyLog(data);
    successMsg = "新增每日状况记录成功！";
  } else if (drawer.type === "edit") {
    apiCall = updateDailyLog(drawer.id, data);
    successMsg = "编辑每日状况记录成功！";
  }
  try {
    const res = await apiCall;
    if (res.code === 0) {
      ElMessage.success(res.msg || successMsg);
      drawer.visible = false;
      Object.assign(formData, defaultFormData);
      loadDailyLogList(true);
      loadCoreStats();
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    const backendErrorMsg =
      error.response && error.response.data && error.response.data.msg
        ? error.response.data.msg
        : error.message || "提交失败，请检查网络或后端服务";
    ElMessage.error(backendErrorMsg);
  }
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `此操作将删除【${row.log_date} ${row.eat_time_text}】的每日状况记录，是否继续?`,
    "警告：删除",
    {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "error",
      dangerouslyUseHTMLString: true,
    }
  )
    .then(async () => {
      try {
        const res = await deleteDailyLog(row.id);

        if (res.code === 0) {
          ElMessage.success(res.msg || "记录删除成功！");
          loadDailyLogList();
          loadCoreStats();
        } else {
          ElMessage.error(res.msg || `删除操作失败`);
        }
      } catch (error) {
        console.error(`删除失败:`, error);
        ElMessage.error(`删除操作失败，请检查网络或后端服务`);
      }
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
};

// 分页事件处理
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  loadDailyLogList(true);
};

const handleCurrentChange = (val) => {
  queryParams.page = val;
  loadDailyLogList();
};

const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex >= 3 && columnIndex <= 11) {
    let backgroundColor = "";

    if (columnIndex === 3 || columnIndex === 4) {
      backgroundColor = "#E6F7FF"; // 浅蓝色
    } else if (columnIndex >= 5 && columnIndex <= 7) {
      backgroundColor = "#FFFBE6"; // 浅黄色
    } else if (columnIndex === 8 || columnIndex === 9) {
      backgroundColor = "#F6FFED"; // 浅绿色
    } else if (columnIndex === 10 || columnIndex === 11) {
      backgroundColor = "#FEF0F0"; // 粉色
    }

    if (backgroundColor) {
      return {
        "background-color": backgroundColor,
        padding: "8px 0",
      };
    }
  }

  return {};
};

onMounted(() => {
  initialLoad();
});
</script>
<template>
  <div class="daily-log-container">
    <el-card class="main-card" shadow="never">
      <div class="card-header">
        <h3>
          <el-icon style="color: black"><DataLine /></el-icon> 经营状况
        </h3>
        <el-button type="primary" :icon="Plus" @click="openDrawer('add')">
          新增记录
        </el-button>
      </div>
      <DailyStatsCard :stats-data="coreStats" :loading="loading" />

      <el-form :inline="true" :model="searchForm" class="filter-form-inline">
        <el-row :gutter="24">
          <el-col :span="4">
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="searchForm.startDate"
                type="date"
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="searchForm.endDate"
                type="date"
                placeholder="结束日期"
                value-format="YYYY-MM-DD"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3.5" class="action-buttons-col">
            <el-form-item>
              <el-button @click="quickDateSelect('week')" plain>
                最近一周
              </el-button>
              <el-button @click="quickDateSelect('month')" plain>
                最近一月
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="按星期">
              <el-select
                v-model="searchForm.log_week"
                placeholder="全部"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in weekOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="按时段">
              <el-select
                v-model="searchForm.eat_time"
                placeholder="全天"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in eatTimeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" class="action-buttons-col">
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="handleSearch">
                搜索
              </el-button>
              <el-button @click="handleReset" :icon="RefreshRight">
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        header-cell-class-name="table-header-cell"
        row-class-name="custom-table-row"
        class="data-table-main"
        :cell-style="cellStyle"
      >
        <el-table-column
          label="序号"
          type="index"
          width="55"
          align="center"
          :index="indexMethod"
        />
        <el-table-column
          prop="log_date"
          label="日期"
          width="105"
          align="center"
          sortable
        />
        <el-table-column
          prop="log_week"
          label="星期"
          width="70"
          align="center"
        />

        <el-table-column label="学校学生包餐" align="center">
          <el-table-column
            prop="meal_count"
            label="人数"
            width="55"
            align="center"
          />
          <el-table-column label="营业额预估(元)" min-width="95" align="center">
            <template #default="scope">
              ¥{{ formatCurrency(scope.row.meal_sales) }}
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="教工及培训部学生用餐" align="center">
          <el-table-column label="扫码" width="95" align="center">
            <template #default="scope">
              {{ scope.row.qcode_count || 0 }}人<br />
              ¥{{ formatCurrency(scope.row.qcode_sales) }}
            </template>
          </el-table-column>
          <el-table-column label="卡机支付" width="95" align="center">
            <template #default="scope">
              {{ scope.row.card_count || 0 }}人<br />
              ¥{{ formatCurrency(scope.row.card_sales) }}
            </template>
          </el-table-column>
          <el-table-column label="饭票挂账" width="95" align="center">
            <template #default="scope">
              {{ scope.row.ticket_count || 0 }}人<br />
              ¥{{ formatCurrency(scope.row.ticket_sales) }}
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="汇总" align="center">
          <el-table-column label="总营业额(元)" min-width="95" align="center">
            <template #default="scope">
              ¥{{ formatCurrency(scope.row.total_sales) }}
            </template>
          </el-table-column>
          <el-table-column label="食材成本/占比" min-width="95" align="center">
            <template #default="scope">
              ¥{{ formatCurrency(scope.row.food_cost) }}<br />
              <el-tag
                :type="
                  Number(scope.row.food_cost_ratio) >= 0.5 ? 'danger' : 'info'
                "
                size="small"
                style="margin-left: 5px"
              >
                {{ formatRatio(scope.row.food_cost_ratio) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="包间" align="center">
          <el-table-column label="营业额(元)" min-width="95" align="center">
            <template #default="scope">
              ¥{{ formatCurrency(scope.row.room_food_sales) }}
            </template>
          </el-table-column>
          <el-table-column label="食材成本/占比" min-width="95" align="center">
            <template #default="scope">
              ¥{{ formatCurrency(scope.row.room_food_cost) }}<br />
              <el-tag
                :type="
                  Number(scope.row.room_food_ratio) >= 0.5 ? 'danger' : 'info'
                "
                size="small"
                style="margin-left: 5px"
              >
                {{ formatRatio(scope.row.room_food_ratio) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column
          label="操作"
          min-width="170"
          fixed="right"
          align="center"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              :icon="Edit"
              size="default"
              @click="openDrawer('edit', scope.row)"
              >编辑</el-button
            >

            <el-button
              link
              type="info"
              :icon="View"
              size="default"
              @click="openDrawer('view', scope.row)"
              >查看</el-button
            >

            <el-button
              link
              type="danger"
              :icon="Delete"
              size="default"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container pagination-split">
        <span class="pagination-info">
          共 {{ total }} 条记录，第 {{ queryParams.page }}/{{
            Math.ceil(total / queryParams.pageSize)
          }}
          页
        </span>
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :small="false"
          :disabled="loading"
          :background="true"
          layout=" prev, pager, next, sizes,jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <Drawer
      v-model="drawer.visible"
      :title="drawer.title"
      :type="drawer.type"
      :size="650"
      @save="handleSave"
      @cancel="handleCancel"
      @close-request="handleCloseDrawer"
    >
      <template #default>
        <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="130px"
          label-position="right"
          :disabled="drawer.type === 'view'"
          :class="{ 'in-view-mode': drawer.type === 'view' }"
        >
          <h4 class="form-section-title section-padding-bottom">基本信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="日期" prop="log_date" required>
                <el-date-picker
                  v-model="formData.log_date"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="就餐时段" prop="eat_time" required>
                <el-select
                  v-model="formData.eat_time"
                  placeholder="选择时段"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in eatTimeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <h4 class="form-section-title section-padding-bottom">包餐</h4>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="包餐人数" prop="meal_count">
                <el-input-number
                  v-model="formData.meal_count"
                  :min="0"
                  controls-position="right"
                  placeholder="输入包餐人数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="包餐营业额(元)" prop="meal_sales">
                <el-input
                  v-model="formData.meal_sales"
                  placeholder="输入包餐营业额"
                  type="number"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <h4 class="form-section-title section-padding-bottom">
            教工及培训部学生用餐
          </h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="扫码人数" prop="qcode_count">
                <el-input-number
                  v-model="formData.qcode_count"
                  :min="0"
                  controls-position="right"
                  placeholder="输入扫码人数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="扫码营业额(元)" prop="qcode_sales">
                <el-input
                  v-model="formData.qcode_sales"
                  placeholder="输入扫码营业额"
                  type="number"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="刷卡人数" prop="card_count">
                <el-input-number
                  v-model="formData.card_count"
                  :min="0"
                  controls-position="right"
                  placeholder="输入刷卡人数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="刷卡营业额(元)" prop="card_sales">
                <el-input
                  v-model="formData.card_sales"
                  placeholder="输入刷卡营业额"
                  type="number"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="餐票人数" prop="ticket_count">
                <el-input-number
                  v-model="formData.ticket_count"
                  :min="0"
                  controls-position="right"
                  placeholder="输入餐票人数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="餐票营业额(元)" prop="ticket_sales">
                <el-input
                  v-model="formData.ticket_sales"
                  placeholder="输入餐票营业额"
                  type="number"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <h4 class="form-section-title section-padding-bottom">
            汇总
            <el-button
              v-if="drawer.type === 'add'"
              :loading="loading"
              type="primary"
              size="small"
              @click="fetchCostsForDate()"
              >获取成本
            </el-button>
          </h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="总营业额(元)">
                <el-input
                  :model-value="formatCurrency(computedNonRoomTotalSales)"
                  placeholder="自动计算"
                  type="text"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="食材总成本(元)" prop="food_cost">
                <el-input
                  v-model="formData.food_cost"
                  placeholder="由系统自动计算"
                  type="number"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <h4 class="form-section-title section-padding-bottom">包间</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="包间营业额(元)" prop="room_food_sales">
                <el-input
                  v-model="formData.room_food_sales"
                  placeholder="输入包间营业额"
                  type="number"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="包间食材成本(元)" prop="room_food_cost">
                <el-input
                  v-model="formData.room_food_cost"
                  placeholder="由系统自动计算"
                  type="number"
                  :disabled="true"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <h4 class="form-section-title section-padding-bottom">其他</h4>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="note">
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注信息"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="handleCancel">取消</el-button>
          <el-button
            v-if="drawer.type !== 'view'"
            type="primary"
            @click="handleSave"
            >保存</el-button
          >
        </div>
      </template>
    </Drawer>
  </div>
</template>
<style scoped lang="less">
.daily-log-container {
  min-height: 100%;
  display: flex;
  flex-direction: column;
  // margin-right: -15px;
}

.main-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 18px;
  box-sizing: border-box;

  :deep(.el-card__body) {
    padding: 0px 15px 15px 15px;
  }
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // margin-bottom: 20px;
  border-bottom: 1px solid rgb(217, 217, 217);

  h3 {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    color: rgb(38, 38, 38);

    .el-icon {
      margin-right: 8px;
      font-size: 18px;
      color: rgb(27, 130, 241);
    }
  }
}

.filter-form-inline {
  :deep(.el-row:last-child .el-col) {
    margin-bottom: 0;
  }

  .el-form-item {
    margin-right: 0;
    width: 100%;
  }

  .action-buttons-col {
    display: flex;
    align-items: flex-start;
    padding-bottom: 0;

    .el-form-item {
      margin-bottom: 0;
      display: flex;
      gap: 10px;
    }

    .el-button {
      margin-left: 5px;

      &:first-child {
        margin-left: 0 !important;
      }
    }
  }
}

.pagination-split {
  margin-top: 18px;
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .pagination-info {
    color: rgb(89, 89, 89);
    font-size: 14px;
    line-height: 28px;
  }

  :deep(.el-pagination) {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;

    .el-pagination__total {
      display: none;
    }

    .el-pagination__sizes,
    .el-pagination__jump {
      display: inline-flex;
      align-items: center;
      margin-left: 10px;
      .el-input__inner {
        height: 30px;
        line-height: 30px;
        min-width: 30px;
        border-radius: 6px;
      }
    }

    .btn-prev,
    .btn-next,
    .el-pager li {
      background: white;
      border: 1px solid rgb(217, 217, 217);
      border-radius: 6px;
      color: rgb(38, 38, 38);
      min-width: 30px;
      height: 30px;
      line-height: 30px;
      padding: 0 10px;
      margin-right: 1px;
    }

    .el-pager li.is-active {
      background: rgb(27, 130, 241);
      border-color: rgb(27, 130, 241);
      color: white;
    }
  }
}

:deep(.el-drawer__body) {
  padding: 0 25px 20px 25px;
}

.form-section-title {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
  margin: 0;
  padding-bottom: 8px;
  border-bottom: 1px solid rgb(217, 217, 217);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 10px;
}

.section-padding-bottom {
  margin-bottom: 20px;
}

:deep(.data-table-main) {
  .el-table__cell {
    padding: 8px 0 !important;
    vertical-align: middle !important;
    border-right: 1px solid #dcdfe6;
    border-bottom: 1px solid #dcdfe6;
  }

  .el-table__row:hover > td {
    background-color: rgb(248, 248, 248) !important;
  }

  .el-table__header-wrapper th {
    height: 50px;
    color: black;
    background: rgba(248, 248, 248) !important;
    font-size: 14px;
    font-weight: 600;
    border-bottom: 1px solid #dcdfe6;
  }
}

.el-form :deep(.el-input-number.is-controls-right .el-input__wrapper) {
  padding-left: 0px;
}
</style>
